package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @Author: xrl
 * @Date: 2022/10/19  17:59
 * @Version 1.0
 */
@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {

    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public long addTask(Task task) {
        //1.添加任务到数据库中
        boolean success = addTaskToDb(task);
        if (success) {
            //2.将任务添加到redis
            addTaskToCache(task);
        }
        return task.getTaskId();
    }


    @Autowired
    private CacheService cacheService;

    /**
     * 将任务添加到redis
     *
     * @param task
     */
    private void addTaskToCache(Task task) {
        //拼接key值
        String key = task.getTaskType() + "_" + task.getPriority();
        //获取5分钟后的毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long timeInMillis = calendar.getTimeInMillis();
        //如果任务的执行时间小于等于当前时间，就存入list
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            //TOPIC="topic_"; 代表当前数据key前缀
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if (task.getExecuteTime() <= timeInMillis) {
            //任务的执行时间大于等于当前时间 && 小于等于预设时间(未来5分钟)，则存入zset中
            //TOPIC="topic_"代表 未来数据key前缀
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }
    }

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    /**
     * 添加任务到数据库中
     *
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {
        //初始状态设为false
        boolean flag = false;
        try {
            //保存任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            //设置不同的属性
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            //保存
            taskinfoMapper.insert(taskinfo);

            //设置taskID
            task.setTaskId(taskinfo.getTaskId());
            //保存到日志表
            TaskinfoLogs logs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, logs);
            logs.setVersion(1);
            logs.setStatus(ScheduleConstants.SCHEDULED);
            //保存
            taskinfoLogsMapper.insert(logs);
            flag = true;
        } catch (BeansException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 取消任务
     *
     * @param taskId 任务id
     * @return 取消结果
     */
    @Override
    public boolean cancelTask(long taskId) {
        //初始状态设置为false
        boolean flag = false;
        //删除任务，更新任务日志
        Task task = updateDb(taskId, ScheduleConstants.CANCELLED);
        //删除Redis中的数据
        if (task != null) {
            removeTaskFromCache(task);
            flag = true;
        }
        return flag;
    }

    /**
     * 删除Redis中的数据
     *
     * @param task
     */
    private void removeTaskFromCache(Task task) {
        //拼接key值
        String key = task.getTaskId() + "_" + task.getPriority();
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            //删除当前数据 list
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        } else {
            //删除未来数据 zset
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }

    /**
     * 删除任务，更新任务日志
     *
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(long taskId, int status) {
        //删除任务
        taskinfoMapper.deleteById(taskId);
        //更新任务日志
        TaskinfoLogs logs = taskinfoLogsMapper.selectById(taskId);
        logs.setStatus(status);
        taskinfoLogsMapper.updateById(logs);
        Task task = new Task();
        BeanUtils.copyProperties(logs, task);
        //设置特有属性
        task.setExecuteTime(logs.getExecuteTime().getTime());
        return task;
    }

    /**
     * 按照类型和优先级来拉取任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        String key = type + "_" + priority;
        //从redis拉取任务
        String json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
        Task task = null;
        if (StringUtils.isNotBlank(json)) {
            task = JSON.parseObject(json, Task.class);
            //更新数据库信息
            updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);
        }
        return task;
    }

    /**
     * 未来数据定时刷新
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
        //加锁解决 分布式情况下,线程抢占问题
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);

        if (StringUtils.isNotBlank(token)) {
            log.info("未来数据定时刷新---定时任务");
            //获取所有未来数据的集合key
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");

            //非空判断
            if (null != futureKeys && futureKeys.size() > 0) {
                for (String futureKey : futureKeys) {   //future_100_50
                    //获取当前数据的key  topic
                    String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                    //按照key和分值查询符合条件的数据
                    Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                    //同步数据
                    if (!tasks.isEmpty()) {
                        //代表有 过期的任务,在zset 未来数据队列 中删除,添加到list消费队列中
                        cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                    }
                }
            }

        }
    }

    /**
     * 数据库任务定时同步到redis
     */
    @PostConstruct
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData() {
        //清理缓存中的数据
        clearCaChe();

        //查询符合条件的任务 小于未来5分钟的任务
        //获取5分钟之后的时间毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        LambdaQueryWrapper<Taskinfo> wrapper = Wrappers.<Taskinfo>lambdaQuery()
                .lt(Taskinfo::getExecuteTime, calendar.getTime());//小于5分钟
        //查询
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(wrapper);
        //把任务添加到redis
        if (null != taskinfos && taskinfos.size() > 0) {
            for (Taskinfo taskinfo : taskinfos) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                //添加到redis
                addTaskToCache(task);
            }
        }
        log.info("数据库任务已经同步到了redis中");
    }

    /**
     * 清理缓存中的数据
     */
    public void clearCaChe() {
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        //删除
        cacheService.delete(topicKeys);
        cacheService.delete(futureKeys);
    }
}
